import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log

object BluetoothReceiver : BroadcastReceiver() {

    private var onDeviceDiscovered: ((BluetoothDevice) -> Unit)? = null
    private var onPairingCompleted: ((BluetoothDevice) -> Unit)? = null
    private var onConnectionStateChanged: ((BluetoothDevice, Boolean) -> Unit)? = null

    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent == null) return

        when (intent.action) {
            // 发现蓝牙设备
            BluetoothDevice.ACTION_FOUND -> {
                val device: BluetoothDevice? =
                    intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                device?.let {
                    Log.d("BluetoothReceiver", "发现设备: ${it.name} (${it.address})")
                    onDeviceDiscovered?.invoke(it)
                }
            }

            // 蓝牙设备配对状态改变
            BluetoothDevice.ACTION_BOND_STATE_CHANGED -> {
                val device: BluetoothDevice? =
                    intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                val bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1)
                if (bondState == BluetoothDevice.BOND_BONDED) {
                    device?.let {
                        Log.d("BluetoothReceiver", "设备已配对: ${it.name} (${it.address})")
                        onPairingCompleted?.invoke(it)
                    }
                }
            }

            // 蓝牙设备连接
            BluetoothDevice.ACTION_ACL_CONNECTED -> {
                val device: BluetoothDevice? =
                    intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                device?.let {
                    Log.d("BluetoothReceiver", "设备已连接: ${it.name} (${it.address})")
                    onConnectionStateChanged?.invoke(it, true)
                }
            }

            // 蓝牙设备断开连接
            BluetoothDevice.ACTION_ACL_DISCONNECTED -> {
                val device: BluetoothDevice? =
                    intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                device?.let {
                    Log.d("BluetoothReceiver", "设备已断开连接: ${it.name} (${it.address})")
                    onConnectionStateChanged?.invoke(it, false)
                }
            }
        }
    }

    /**
     * 设置设备发现监听器
     */
    fun setOnDeviceDiscoveredListener(listener: (BluetoothDevice) -> Unit) {
        onDeviceDiscovered = listener
    }

    /**
     * 设置配对完成监听器
     */
    fun setOnPairingCompletedListener(listener: (BluetoothDevice) -> Unit) {
        onPairingCompleted = listener
    }

    /**
     * 设置连接状态变化监听器
     */
    fun setOnConnectionStateChangedListener(listener: (BluetoothDevice, Boolean) -> Unit) {
        onConnectionStateChanged = listener
    }
}
